package com.zhuangxiaoyan.springbootredis.bloomfilter.controller;

import com.zhuangxiaoyan.springbootredis.bloomfilter.service.BloomFiliterService;
import com.zhuangxiaoyan.springbootredis.delayqueuing.entity.Job;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Classname BloomFilterController
 * @Description TODO
 * @Date 2022/4/18 22:23
 * @Created by xjl
 */
@RestController
@RequestMapping("bloom")
public class BloomFilterController {

    @Autowired
    private BloomFiliterService bloomFiliterService;

    /**
     * 添加元素
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "test", method = RequestMethod.POST)
    public void addBloomFiliter(Job request) {
        Set<String> set = new HashSet<String>(1000);
        List<String> list = new ArrayList<String>(1000);
        //向布隆过滤器中填充数据，为了测试真实，我们记录了 1000 个 uuid，另外 9000个作为干扰数据
        for (int i = 0; i < 10000; i++) {
            String uuid = UUID.randomUUID().toString();
            if (i < 1000) {
                set.add(uuid);
                list.add(uuid);
            }
            bloomFiliterService.bloomAdd(uuid);
        }
        int wrong = 0; // 布隆过滤器误判的次数
        int right = 0;// 布隆过滤器正确次数
        for (int i = 0; i < 10000; i++) {
            String str = i % 10 == 0 ? list.get(i / 10) : UUID.randomUUID().toString();
            if (bloomFiliterService.bloomExist(str)) {
                if (set.contains(str)) {
                    right++;
                } else {
                    wrong++;
                }
            }
        }
        System.out.println("right:" + right);
        //因为误差率为3%，所以一万条数据wrong的值在30左右
        System.out.println("wrong:" + wrong);
    }
}
